package common

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"net/url"
	"time"
)

var DB *gorm.DB
var SqlDB *sql.DB

// https://gorm.io/zh_CN/docs/index.html
func InitDB() *gorm.DB {
	//从配置文件中读取数据库配置信息
	host := viper.GetString("datasource.host")
	port := viper.Get("datasource.port")
	database := viper.GetString("datasource.database")
	username := viper.GetString("datasource.username")
	password := viper.GetString("datasource.password")
	charset := viper.GetString("datasource.charset")
	loc := viper.GetString("datasource.loc")
	args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true&loc=%s",
		username,
		password,
		host,
		port,
		database,
		charset,
		url.QueryEscape(loc))
	//fmt.Println(args)
	db, err := gorm.Open(mysql.Open(args), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info), //配置日志级别，打印出所有的sql
	})
	if err != nil {
		fmt.Println(err)
		panic("failed to connect database, err: " + err.Error())
	}
	DB = db
	return db
}

func InitSqlDB() error {
	//从配置文件中读取数据库配置信息
	host := viper.GetString("datasource.host")
	port := viper.Get("datasource.port")
	database := viper.GetString("datasource.database")
	username := viper.GetString("datasource.username")
	password := viper.GetString("datasource.password")
	charset := viper.GetString("datasource.charset")
	loc := viper.GetString("datasource.loc")

	//dsn := "root:123456@tcp(127.0.0.1:3306)/message_db?parseTime=true"
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true&loc=%s",
		username,
		password,
		host,
		port,
		database,
		charset,
		url.QueryEscape(loc))
	var err error
	SqlDB, err = sql.Open("mysql", dsn)
	if err != nil {
		return err
	}
	// 连接池配置
	SqlDB.SetMaxOpenConns(20)
	SqlDB.SetMaxIdleConns(10)
	SqlDB.SetConnMaxLifetime(30 * time.Minute)
	return SqlDB.Ping()
}
func CloseSqlDB() {
	if SqlDB != nil {
		SqlDB.Close()
	}
}
